<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use app\index\model\Users;
use app\index\model\Messages;
use think\response\Json;


class User extends Typez
{
   public function index(){
       $user_id = input('id');
       $res = db('article')
           ->where('m.user_id', $user_id)
           ->alias('a')
           ->field('a.title,a.id,a.author,m.user_id')
           ->join('lan_messages m', 'a.id=m.article_id')
           ->group('id')
           ->select();

       foreach ($res as $k => $v){
           $res[$k]['messages'] = db('messages')
               ->where(['article_id' => $v['id'], 'user_id' => $v['user_id']])
               ->select();
       }

       $user = Users::get(['id' => $user_id]);

       $user_mess = db('messages')
           ->where('article_id', 0)
           ->where('user_id', $user_id)
           ->order('create_time desc')
           ->select();


//       return json(['code' => 0, 'msg' => '', 'data' => $res]);
       $this->assign(array(
           'user' => $user,
           'article_message' => $res,
           'user_mess' => $user_mess
       ));
       return view();
   }

   public function edit(){
       if (\request()->isPost()){
           $data = input('post.');
           $user = Users::get(['id' => $data['id']]);
           if (!$user){
               return json(['code' => 0, 'msg' => '用户未找到']);
           }

           if ($data['password'] == ''){
               $data['password'] = $user['password'];
           }else{
               $data['password'] = md5($data['password']);
           }

           $res = Users::update($data);
           if (!$res){
               return json(['code' => 0, 'msg' => '修改失败']);
           }
           return json(['code' => 1, 'msg' => '修改成功，重新登录']);
       }
       $id = input('id');
       $user = Users::get(['id' => $id]);
       $this->assign('user', $user);
       return view();
   }
}
